package com.jy.util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DbUtil {
	private final static String DRIVER = "com.mysql.jdbc.Driver";
	private final static String URL = "jdbc:mysql://localhost:3306/authority?useUnicode=true&characterEncoding=UTF-8";
	private final static String USERNAME = "root";
	private final static String PWD = "root";

	public static Connection getconn() {
		Connection conn = null;
		// 加载驱动
		try {
			Class.forName(DRIVER);
			conn = DriverManager.getConnection(URL, USERNAME, PWD);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	// 释放资源
	public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {

		try {
			if (conn != null) {
				conn.close();
			}
			if (ps != null) {
				ps.close();
			}
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// 通用查询
	public static List selectTable(String sql, Class c,Object... param) throws Exception {
		List list = new ArrayList();
		Connection conn = DbUtil.getconn();
		PreparedStatement ps = conn.prepareStatement(sql);
		for (int i = 1; i <= param.length; i++) {
			ps.setObject(i, param[i - 1]);
		}
		ResultSet rs = ps.executeQuery();
		// 得到查询的字段名 --元数据
		ResultSetMetaData rsmd = rs.getMetaData();
		int cols = rsmd.getColumnCount();
		if (cols != c.getDeclaredFields().length) {
			System.out.println("字段与属性的个数不一致");
		}
		while (rs.next()) {
			Object obj = c.newInstance();
			for (int i = 1; i <= cols; i++) {
				String name = rsmd.getColumnName(i);
				// System.out.println("列名:"+name);
				Object val = rs.getObject(name);
				Field f = c.getDeclaredField(name);
				f.set(obj, val);
			}
			list.add(obj);// 放入集合
		}
		return list;
	}

	// 通用更新语句
	public int update(String sql, Object... param) throws SQLException {
		Connection conn = DbUtil.getconn();
		PreparedStatement ps = conn.prepareStatement(sql);
		for (int i = 1; i <= param.length; i++) {
			ps.setObject(i, param[i - 1]);
		}
		int n = ps.executeUpdate();
		DbUtil.close(conn, ps, null);
		return n;
	}
}
